#coding: utf-8
# __author__ = 'wenke1'

import os
import sys
from SimpleXMLRPCServer import SimpleXMLRPCServer
from urlparse import urlparse

class FileNode(object):
    def __init__(self,ip,port,nodedir,passwd):
        self.ip=ip
        self.port=port
        self.nodedir=nodedir
        self.passwd=passwd
    def listDir(self,querydir):
        #return all files in the sharedir
        return os.listdir(querydir)
    def _queryFile(self,queryfile):
        #查询file是否存在，存在返回成功和文件内容
        code='succ' if queryfile in os.listdir(self.nodedir) else 'fail'
        if code=='succ':
            with open(queryfile) as f:
                filedata=f.read()
        else:
            print "file error"
            filedata=None
        return code,filedata
    def getFile(self,queryfile,passwd):
        ''':return
        0:获取file成功
        1:失败
        '''
        if passwd==self.passwd:
            print "passwd is ok"
            code,data=self._queryFile(queryfile)
        else:
            print "passwd incorrect"
            return 1
        if code=='succ':
            print(data)
            with open(queryfile,mode='w') as outf:
                outf.write(data)
            return 0
        else:
            return 1
    def _start(self):
        #启动共享服务
        node=SimpleXMLRPCServer((self.ip,self.port))
        node.register_instance(self)
        print "-------------start server--------------"
        node.serve_forever()
def parseUrl(url):
    #get ip,port from url
    name=urlparse(url)[1]
    addr=name.split(':')
    ip,port=addr[0],addr[1]
    return ip,int(port)
if __name__=="__main__":
    #启动一个实例
    url,sharedir,passwd=sys.argv[1:]
    ip,port=parseUrl(url)
    filenode=FileNode(ip,port,sharedir,passwd)
    filenode._start()
